//
//  LHReadCommentController.m
//  EPA
//
//  Created by 卢浩 on 16/4/25.
//  Copyright © 2016年 卢浩. All rights reserved.
//

#import "LHReadCommentController.h"
#import "LHReadCommentModel.h"
#import "LHUserInfoManager.h"
#import "LHReadCommentCell.h"
#import "LHMenuViewController.h"

@interface LHReadCommentController ()

@property (nonatomic,strong) NSMutableArray *dataSource;

@property (nonatomic,strong) UITextField *textFile;

@end

@implementation LHReadCommentController

- (void)addCommentAction{
    if ([LHUserInfoManager shareManager].uid) {
        UIAlertController *alertC = [UIAlertController alertControllerWithTitle:@"评论:" message:@"请输入评论内容:" preferredStyle:(UIAlertControllerStyleAlert)];
        [alertC addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
            self.textFile = textField;
        }];
        [alertC addAction:[UIAlertAction actionWithTitle:@"发表" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
            if (self.textFile.text.length > 0) {
                [self addCommentWithContendId:self.contentid Content:self.textFile.text];
            }else{
                NSLog(@"内容不能为空!");
            }
        }]];
        [alertC addAction:[UIAlertAction actionWithTitle:@"取消" style:(UIAlertActionStyleCancel) handler:nil]];
        [self presentViewController:alertC animated:YES completion:nil];
    }else{
        UIAlertController *alertC = [UIAlertController alertControllerWithTitle:@"提示" message:@"您还未登陆哦!" preferredStyle:(UIAlertControllerStyleAlert)];
        [alertC addAction:[UIAlertAction actionWithTitle:@"登陆" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
            [[LHMenuViewController getMenuViewController] showLoginVC];
        }]];
        [alertC addAction:[UIAlertAction actionWithTitle:@"取消" style:(UIAlertActionStyleCancel) handler:nil]];
        [self presentViewController:alertC animated:YES completion:nil];
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.dataSource = [NSMutableArray array];
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:(UIBarButtonSystemItemAdd) target:self action:@selector(addCommentAction)];
    
    [self getCommentWithContendId:self.contentid];
}

- (void)getCommentWithContendId:(NSString *)contentId{
    NSURL *url = [NSURL URLWithString:@"http://api2.pianke.me/comment/get"];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    request.HTTPMethod = @"POST";
    request.HTTPBody = [[NSString stringWithFormat:@"auth=%@&client=1&contentid=%@&deviceid=6D4DD967-5EB2-40E2-A202-37E64F3BEA31&limit=10&start=0&version=3.0.6",[LHUserInfoManager shareManager].auth,contentId] dataUsingEncoding:NSUTF8StringEncoding];
    NSURLSessionDataTask *dataTask = [[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if (data) {
            NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingMutableContainers) error:nil];
            //            NSLog(@"%@",dict);
            NSDictionary *dataDict = dict[@"data"];
            NSArray *listArr = dataDict[@"list"];
            [self.dataSource removeAllObjects];
            for (NSDictionary *commentDict in listArr) {
                LHReadCommentModel *model = [[LHReadCommentModel alloc]init];
                [model setValuesForKeysWithDictionary:commentDict];
                [self.dataSource addObject:model];
            }
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.tableView reloadData];
            });
        }
    }];
    [dataTask resume];
}

- (void)addCommentWithContendId:(NSString *)contentId Content:(NSString *)content{
    NSURL *url = [NSURL URLWithString:@"http://api2.pianke.me/comment/add"];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    request.HTTPMethod = @"POST";
    request.HTTPBody = [[NSString stringWithFormat:@"auth=%@&client=1&content=%@&contentid=%@&deviceid=6D4DD967-5EB2-40E2-A202-37E64F3BEA31&recid=&reuid=&version=3.0.6",[LHUserInfoManager shareManager].auth,content,contentId] dataUsingEncoding:NSUTF8StringEncoding];
    NSURLSessionDataTask *dataTask = [[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if (data) {
            NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingMutableContainers) error:nil];
            //            NSLog(@"%@",dict);
            [self showAlertControllerWithStr:dict[@"data"][@"msg"]];
            dispatch_async(dispatch_get_main_queue(), ^{
                [self getCommentWithContendId:self.contentid];
            });
        }
    }];
    [dataTask resume];
}

- (void)showAlertControllerWithStr:(NSString *)str{
    dispatch_async(dispatch_get_main_queue(), ^{
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示信息" message:str preferredStyle:(UIAlertControllerStyleAlert)];
        [alertController addAction:[UIAlertAction actionWithTitle:@"确定" style:(UIAlertActionStyleDefault) handler:nil]];
        [self presentViewController:alertController animated:YES completion:nil];
    });
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataSource.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    LHReadCommentCell *cell = [tableView dequeueReusableCellWithIdentifier:@"LHReadCommentCell" forIndexPath:indexPath];
    cell.model = self.dataSource[indexPath.row];
    return cell;
}

@end
